package com.cyw.common.config.mybatis.handler.base;

import com.cyw.common.utils.JsonUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Author:cyw
 * @CreateTime: 2021/3/3 17:18
 **/
@MappedTypes(Object.class)
@MappedJdbcTypes(value = {JdbcType.BLOB, JdbcType.VARCHAR, JdbcType.CHAR})
public abstract class JsonTypeHandler<T> extends BaseTypeHandler<T> {

    private final Class<T> type;

    public JsonTypeHandler(Class<T> type) {
        this.type = type;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, serializer(parameter));
    }

    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return deserializer(rs.getString(columnName));
    }

    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return deserializer(rs.getString(columnIndex));
    }

    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return deserializer(cs.getString(columnIndex));
    }

    private String serializer(T parameter) {
        return JsonUtils.toJsonIfPresent(parameter);
    }

    private T deserializer(String info) {
        return JsonUtils.toObjectIfPresent(info, type);
    }
}

    
    
    
    
    
    
    
    
    

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    